package com.cx330.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.UUID;

@Component
public class OnceTokenGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {
    @Override
    public GatewayFilter apply(NameValueConfig config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                    ServerHttpResponse response = exchange.getResponse();
                    HttpHeaders headers = response.getHeaders();
                    String value = config.getValue();
                    if ("uuid".equalsIgnoreCase(value)) {
                        value = UUID.randomUUID().toString();
                    }
                    if ("jwt".equalsIgnoreCase(value)) {
                        value = "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImxhYklkIjpudWxsLCJuYW1lIjoi6LaF566hIiwiZGVwdElkIjoiMTAxIiwibGFiTmFtZSI6bnVsbCwic2VhdElkIjpudWxsLCJ1c2VyaWQiOiIxIiwibG9naW5fdXNlcl9rZXkiOiIyNjU2MWM4ZC0xY2NhLTQ1MWItYTcxNi1iZWI0NmI5ZmNjZmYifQ.MdaCrJCAJUQOFAAJxUoYHuviqDDTxxrNQ4_6NL_6O4YddAxEatJWnL-5gvqs0NPTr0G6PQ-6_8rhuLIqmaxK7Q";
                    }
                    headers.add(config.getName(), value);
                }));
            }
        };
    }
}
